package com.thingple.web.bridge.reader;

import android.content.Intent;
import android.os.Bundle;
import android.webkit.WebView;

import com.thingple.eye.ActionResultListener;
import com.thingple.h5.bridge.Bridge;
import com.thingple.h5.bridge.BridgeConfig;
import com.thingple.h5.bridge.JsInvokeHandler;

import java.util.HashMap;
import java.util.Map;

/**
 *
 * 读卡后,处理
 * Created by lism on 2017/8/18.
 */

class ReadCardListener implements ActionResultListener {

    private WebView webView;

    private Bridge jsBridge;

    ReadCardListener(WebView webView, Bridge jsBridge) {

        this.webView = webView;
        this.jsBridge = jsBridge;
    }

    private void onReadCard(String tid, String epc, String user) {
        BridgeConfig bridgeConfig = jsBridge.getClass().getAnnotation(BridgeConfig.class);
        if (bridgeConfig == null) {
            return;
        }
        Map<String, String> paramMap = new HashMap<>();
        if (tid != null) {
            paramMap.put("tid", tid);
        }
        if (epc != null) {
            paramMap.put("epc", epc);
        }
        if (user != null) {
            paramMap.put("user", user);
        }

        String module = bridgeConfig.moduleName() + "_listener";
        String funcName = "onReadCard";
        JsInvokeHandler jsInvokeHandler = new JsInvokeHandler(webView);
        jsInvokeHandler.module(module)
                .function(funcName)
                .params(paramMap)
                .invoke();
    }

    @Override
    public void onResponse(int requestCode, int resultCode, Intent data) {
        if (data != null) {
            Bundle bundle = data.getExtras();
            if (bundle != null) {
                String tid = bundle.getString("TID");
                String epc = bundle.getString("EPC");
                String user = bundle.getString("USER");
                onReadCard(tid, epc, user);
            }
        }
    }
}
